<?php

namespace app\common\entity;

use app\common\service\Users\Cache;
use think\Db;
use think\Model;
use app\common\entity\Category;
use app\common\entity\UserProduct;
use app\common\entity\Divide;


class User extends Model
{

    const STATUS_DEFAULT = 1;
    const STATUS_FORBIDDED = -1;
    const AUTH_SUCCESS = 1;
    const AUTH_ERROR = -1;

    protected $createTime = 'register_time';
    protected $login_time = 'login_time';

    protected $categoryModel;
    /**
     * @var string 对应的数据表名
     */
    protected $table = 'user';
    protected $autoWriteTimestamp = true;

    public function getId()
    {
        return $this->id;
    }

    public function getCategoryModel()
    {
        if (!$this->categoryModel) {
            $this->categoryModel = new Category();
        }
        return $this->categoryModel;
    }

    /**
     * 获取金库值
     */
    public function getBonus()
    {
        return $this->bonus;
    }

    /**
     * 获取用户名
     */
    public function getName()
    {
        return $this->name;;
    }

    /**
     * @param $userId
     * @return 获取用户名
     */
    public function getNameByUserId($userId)
    {
        return $this->where(array('id' => $userId))->value('nick_name');
    }

    /**
     * @param $userId
     * @return 获取用户手机号
     */
    public function getMobileByUserId($userId)
    {
        return $this->where(array('id' => $userId))->value('mobile');
    }

    /**
     * 获取用户手机
     */
    public function getMobile()
    {
        return $this->mobile;
    }

    /**
     * 获取密码
     */
    public function getPassword()
    {
        return $this->password;
    }

    public function getSafePassword()
    {
        return $this->trad_password;
    }

    /**
     * 获取禁用时间
     */
    public function getForbiddenTime()
    {
        return $this->forbidden_time ? date('Y-m-d H:i:s', $this->forbidden_time) : 0;
    }

    /**
     * 判断是否被禁用
     */
    public function isForbiddened()
    {
        return $this->forbidden_time ? true : false;
    }

    /**
     * 获取注册时间
     */
    public function getRegisterTime()
    {
        return $this->register_time;
    }

    /**
     * 获取最后登录时间
     */
    public function getLoginTime()
    {
        return $this->login_time;
    }

    public static function getAllLevel()
    {
        return [
            0 => '普卡会员',
            1 => '普卡会员',
            2 => '银卡会员',
            3 => '金卡会员',
            4 => '钻卡会员',
            5 => '合伙人',
        ];
    }


    public function getLevel()
    {

        switch ($this->level) {
            case 0:
                return '普卡会员';
            case 1:
                return '普卡会员';
            case 2:
                return '银卡会员';
            case 3:
                return '金卡会员';
            case 4:
                return '钻卡会员';
            case 5:
                return '合伙人';

            default:
                return '';
        }
    }


    public static function getOneLevel($level)
    {

        switch ($level) {
            case 0:
                return '普卡会员';
            case 1:
                return '普卡会员';
            case 2:
                return '银卡会员';
            case 3:
                return '金卡会员';
            case 4:
                return '钻卡会员';
            case 5:
                return '合伙人';
            default:
                return '';
        }
    }

    public static function checkMobile($mobile)
    {
        return self::where('mobile', $mobile)->find();
    }

    //获取直推人数
    public function getChildTotal()
    {
        return self::where('pid', $this->getId())->count();
    }

    public function getTeamInfo()
    {
        $categoryModel = $this->getCategoryModel();
        $fids = $categoryModel->getSubChild($this->getId());
        if (isset($fids[0])) {
            unset($fids[0]);
        }
        if ($fids) {
            $totalrate = User::where('id', 'in', $fids)->sum('product_rate');
            return [
                'total' => count($fids),
                'rate' => sprintf('%.5f', $totalrate)
            ];
        } else {
            return ['total' => 0, 'rate' => 0];
        }
    }

    //获取团队算力
    public function getTeamRate($id)
    {
        $categoryModel = $this->getCategoryModel();
        $fids = $categoryModel->getSubChild($id);
        if (isset($fids[0])) {
            unset($fids[0]);
        }
        $totalrate = 0;
        if ($fids) {
            $totalrate = User::where('id', 'in', $fids)->sum('product_rate');
        }
        return sprintf('%.5f', $totalrate);
    }

    //获取购买矿机的下级用户数量
    public function getSubBuyCount()
    {
        $categoryModel = $this->getCategoryModel();
        $fids = $categoryModel->getSubChild($this->getId());
        if (isset($fids[0])) {
            unset($fids[0]);
        }
        $total = 0;
        if ($fids) {
            $total = UserProduct::where('user_id', 'in', $fids)->where('types', UserProduct::TYPE_BUY)->count();
        }
        return $total;
    }

    /**
     * 获取矿机数量
     */
    public function productCount($uid)
    {
        return UserProduct::where("user_id", $uid)->where('status', 1)->count();
    }

    //获取团队的人数
    public function getTeam($memberId, $users)
    {
        $Teams = array(); //最终结果
        $mids = array($memberId); //第一次执行时候的用户id
        do {
            $othermids = array();
            $state = false;
            foreach ($mids as $valueone) {
                foreach ($users as $key => $valuetwo) {
                    if ($valuetwo['pid'] == $valueone) {
                        $Teams[] = $valuetwo['id']; //找到我的下级立即添加到最终结果中
                        $othermids[] = $valuetwo['id']; //将我的下级id保存起来用来下轮循环他的下级
                        //array_splice($users, $key, 1);//从所有会员中删除他
                        $state = true;
                    }
                }
            }
            $mids = $othermids; //foreach中找到的我的下级集合,用来下次循环
        } while ($state == true);

        return $Teams;
    }

    public function getChilds($memberId)
    {
        $childs = self::where('pid', $memberId)
            ->field('*')
            ->select();
        return $childs;
    }

    /**
     * 获取用户上级信息
     */
    public function getParentInfo()
    {
        if ($this->pid == 0) {
            return '';
        }
        $data = self::where('id', $this->pid)->field('nick_name,mobile')->find();

        return $data ? $data : '';
    }

    /**
     * 认证通过推荐奖励
     */
    public function recommendReward($pid)
    {
        $recommendReward = Db::table('config')->where('key', 'recommend_reward')->find();
        $recommendReward = (float)$recommendReward['value'];
        //得到父级信息
        $puser = self::where('id', $pid)->field('nick_name,mobile,magic')->find();
        if ($puser) {
            //如果父级存在就给父级加上推荐奖励
            $res = self::where('id', $pid)->setInc('magic', $recommendReward);
            //增加父级金币的流水记录
            $res1 = UserMagicLog::addInfo($pid, '认证直推奖励', $recommendReward, $puser->magic, $puser->magic + $recommendReward, 7);
            return ['status' => 1, 'recommendReward' => $recommendReward];
        } else {
            return '';
        }
    }

    /**
     * 获取用户冻结的资金
     */
    public function getFreeze()
    {
        //订单表中，用户出售的number和手续费 user_id = 用户id 且 types 为出售 （状态为 2 或者 3 或者为1）
        //获取 target_user_id = 用户id 且 types 为买入 （状态为 2 或者 3 ）

        $model = new Orders();
        $tableName = $model->getTable();
        $sql = <<<SQL
SELECT sum(`number`) as numbers, sum(`charge_number`) as charge_number FROM {$tableName} WHERE user_id={$this->id} AND types = 2 AND status IN (1,2,3) LIMIT 1
SQL;
        $sale = Db::query($sql);

        $sql = <<<SQL
SELECT sum(`number`) as numbers, sum(`charge_number`) as charge_number FROM {$tableName} WHERE target_user_id={$this->id} AND types = 1  AND status IN (2,3) LIMIT 1
SQL;
        $buy = Db::query($sql);

        $freeze = bcadd($sale[0]['numbers'], $sale[0]['charge_number'], 8) + bcadd($buy[0]['numbers'], $buy[0]['charge_number'], 8);

        return [
            'freeze' => $freeze,
            'total' => count($sale[0]['numbers']) + count($buy[0]['numbers'])
        ];
    }

    public function getUsernameByUids($uids)
    {
        return $this->where('id', 'in', $uids)->column('id,nick_name');
    }

    public function getUserInfoByUids($uids, $field = '*')
    {
        if ($field == '*') {
            return $this->where('id', 'in', $uids)->column($field);
        } else {
            return $this->where('id', 'in', $uids)->column('id,' . $field);
        }
    }

    /**
     * 小金库金额变动
     */
    public function setBonus($uid, $types, $change, $remark)
    {

        if (empty($uid) || empty($types) || empty($change)) {
            return;
        }

        //查看用户信息
        $member = self::where('id', $uid)->find();

        if (empty($member)) {
            return;
        }

        $later = bcadd($member[$types], $change, 8);

        //如果操作的数字资产
        if ($types == 'property') {
            $laterReturncoin = $member['returncoin'] + $change;
            $user = new self();
            $user->where('id', $uid)->update(["returncoin" => $laterReturncoin]);
        }

        //插入更新
        $arr = [
            'periods' => 0,
            'user_id' => $uid,
            'types' => $types,
            'orderid' => 0,
            'change' => $change,
            'before' => $member[$types],
            'later' => $later,
            'remark' => $remark,
            'createtime' => time()
        ];

        //插记录
        Db::startTrans();
        try {

            if ($later < 0) {
                throw new \Exception('操作失败');
            }

            $Divide = new Divide();
            $result = $Divide->save($arr);

            if (!$result) {
                throw new \Exception('操作失败');
            }

            $self = new self();
            $self->where('id', $uid)->update(["{$types}" => $later]);

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
        }
        return true;
    }

    /**
     * 随机生成提现单号
     */
    public function setWithdrawNumber($userId)
    {
        return 'WS' . date('Ymd') . $userId . date('His') . rand(1000, 9999);
    }


    #获取下级有多少人
    public function getChildsNum($child, &$count = 0)
    {
        $count1 = count($child);
        $count = $count + $count1;
        // dump($child);die;
        foreach ($child as $v) {
            if ($count1 == 0) {
                return;
            }
            $cc = User::field('id')->where('pid', $v['id'])->where('level', '>=', '0')->select();
            $res = $this->getChildsNum($cc, $count);
        }

        return $count;
    }

    #获取下级
    public function getChildsInfo($uid, $num = 0, &$childs = [], &$level = 0)
    {
//        static $childs = [];
//        static $level = 0;
        if (isset($num)) {
            if ($level == $num) {
                return $childs;
            }
        }
        $child = Db::table('user')->where('pid', $uid)->field('id,register_time,avatar,real_name,mobile,nick_name,mobile,level,pid,status')->select();
        if ($child) {
            $level++;
            $childs[$level] = $child;
            foreach ($child as $v) {

                $this->getChildsInfo($v['id'], $num, $childs, $level);
            }
        }

        return $childs;

    }

    #获取下级有多少人
    public function getChildsNum1($child)
    {
        static $count = 0;
        $count1 = count($child);
        $count = $count + $count1;
        // dump($child);die;
        foreach ($child as $v) {
            if ($count1 == 0) {
                return;
            }
            $cc = User::field('id')->where('pid', $v['id'])->select();
            $res = $this->getChildsNum1($cc);
        }

        return $count;
    }

    #获取下级用户
    public function getChildsInfoId($uid, &$childs = array())
    {

        $child = User::where('pid', $uid)->field('id')->select()->toArray();

        if (!empty($child)) {
            foreach ($child as $v) {
                $childs[] = $v;
                $res = $this->getChildsInfoId($v['id'], $childs);
                if ($res == false) {
                    continue;
                }
            }
        } else {
            false;
        }

        return $childs;

    }

    #获取下3级人数
    public function getChildsInfoThreeNum($uid)
    {
//        static $childs = [];
        static $count = 0;
        static $countTwo = 0;
        static $countThree = 0;
        $childOne = User::where('pid', $uid)->field('id,pid,status')->select();//1
        $countOne = count($childOne);
        $count = $countOne;
        foreach ($childOne as $v) {
            $two = User::where('pid', $v['id'])->field('id,pid,status')->select();//2
            $countTwo = count($two) + $countTwo;
            foreach ($two as $vv) {
                $three = User::where('pid', $vv['id'])->field('id,pid,status')->select();//3
                $countThree = $countThree + count($three);
            }

        }
        $count = $countThree + $countTwo + $count;
        return $count;

    }


    #获取直推人数
    public function getZhitui($uid)
    {
        $num = self::where('pid', $uid)->where('level', '<>', 0)->count();
        return $num;
    }

    #获取等级
    public function getUserLevel($uid)
    {
        $level = self::where('id', $uid)->value('level');
        return $level;
    }

    /**
     * 银行卡号 微信号 支付宝账号 唯一
     */
    public function checkMsg($type, $account, $id = '')
    {
        return self::where("$type", $account)->where('id', '<>', $id)->find();
    }


    static public function fanTree($data, $id){
        $list = array();
        foreach($data as $v) {
            if($v['id'] == $id) {
                $item = self::fanTree($data, $v['pid']);
                array_push($list, $v);
                if(!empty($item)) {
                    $list = array_merge($list, $item);
                }

            }
        }
        return $list;
    }
    static public function tree($data, $id){
        $list = array();
        foreach($data as $v) {
            if($v['pid'] == $id) {
                $item = self::tree($data, $v['id']);
                array_push($list, $v);
                if(!empty($item)) {
                    $list = array_merge($list, $item);
                }

            }
        }
        return $list;
    }

    static function upLevel($uid){
        $user = User::where('id',$uid)->find();
        if($user['level'] == 5 || $user['real_pass'] != 2){
            return true;
        }
        $user_level = UserLevelSend::where('level','>',$user['level'])->order('level desc')->select();
        $order = Orders::where('user_id',$uid)->sum('pay_money');

        $users = self::select();
        $list = self::tree($users,$uid);
        $level1 = 0;$level2 = 0;$level3 = 0;
        foreach($list as $k=>$v){
            if($v['level'] == 1)$level1++;
            if($v['level'] == 2)$level2++;
            if($v['level'] == 3)$level3++;
        }
        $list = implode(',',array_column($list,'id'));
        foreach($user_level as $k=>$v){
            if($order < $v['pay_money']){
                continue;
            }
            if($v['level1'] > $level1){
                continue;
            }
            if($v['level2'] > $level2){
                continue;
            }
            if($v['level3'] > $level3){
                continue;
            }
            User::where('id',$uid)->update(['level'=>$v['level']]);

            return ['msg'=>'用户'.$uid.'升到'.$v['level']."级\n",'level1'=>$level1,'level2'=>$level2,'level3'=>$level3,'order'=>$order,'list'=>$list];
        }

    }

}
